package au.com.koalaclass.exception;

import au.com.koalaclass.entity.AjaxResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mockito.internal.matchers.Null;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Superlu
 * @version 1.0.0
 * @ClassName ResponseResultHandler
 * @Description 统一处理RestController中正常的返回结果
 * @createTime 2021/11/5 13:09
 */
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        System.out.println(body);
        //如果返回为void
        if (body instanceof Null) {
            return AjaxResult.success();
        } else if (body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            String str = null;
            try {
                str = objectMapper.writeValueAsString(AjaxResult.success(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return str;

        } else {
            return AjaxResult.success(body);
        }
    }
}
